﻿using System;
using System.Reflection;
using UnityEngine;

namespace TC
{
    public class ValueOutput<T> : ValuePort
    {
        private Func<T> getter;
        public T Value { get { return getter(); } }
        public override Type type => typeof(T);

        public override bool IsInput => false;
        public override bool AllowMultiConnect => true;

        public ValueOutput(FlowNode parent, string name, Func<T> getter) : base(parent, name)
        {
            this.getter = getter;
        }

        public override bool CanConnect(Port other)
        {
            if (other is ValuePort && other.IsInput && other.type.IsAssignableFrom(type))
            {
                return true;
            }
            return false;
        }

        public override bool CanConnect(Type nodeType, out FieldInfo portInfo)
        {
            var fields = nodeType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            foreach (var field in fields)
            {
                if (field.FieldType == typeof(ValueInput<T>))
                {
                    portInfo = field;
                    return true;
                }
            }
            portInfo = default;
            return false;
        }
    }
}
